#include "input_net.h"
#include "driver_uart.h"
#include "atcommand.h"
#include <string.h>
#include "input_queue.h"
#include <stdio.h>


static char ESP8266_Recv_Buff[100] = {0};
static int  Buff_Index = 0;
static int  Valid_Data_Len = 0;
static RECV_STATUS  RecvFlag =  INIT_STATUS;


static void ESP8266GetInputDataCallBack(char ch)
{
//    printf("%c",ch);
    inputEvent iEvent;
    char *tmp = ESP8266_Recv_Buff;
    int i = Buff_Index;
    int j = 0;
        
    tmp[i] = ch;
    Buff_Index++;
    switch(RecvFlag)
    {
        case INIT_STATUS:
        { 
            if(tmp[0] != '+')
            {
                Buff_Index = 0;
            }
            else if(i == 4)
            {
                if(strcmp(tmp, "+IPD,") == 0)
                {
                    RecvFlag = LENGTH_STATUS;  
                    Buff_Index = 0;
                }      
            }
            break;
        }
        case LENGTH_STATUS:
        {
            if(tmp[i] == ':')
            {
                for(j=0;j<i;j++)
                {
                    Valid_Data_Len = Valid_Data_Len*10 + tmp[j] - '0';
                }
                  RecvFlag = DATA_STATUS;  
                  Buff_Index = 0;  
            }
            break;
        }  
        case DATA_STATUS:
        {        
            if(Buff_Index == Valid_Data_Len)
            {
                iEvent.iType = Type_Net;    
                memmove(iEvent.str, tmp, Valid_Data_Len);
                iEvent.str[Valid_Data_Len] = '\0';
                PutInputEvent(&iEvent);
                printf("%s:%s:%d:%s", __FILE__, __FUNCTION__, __LINE__, iEvent.str);
                
                Buff_Index = 0; 
                Valid_Data_Len = 0;
                RecvFlag = INIT_STATUS;
                memset(ESP8266_Recv_Buff, 0, 100);
            }
            break;  
        }
    }
}


static int NetInputInit(void)
{
   GetNetDataFromISR(ESP8266GetInputDataCallBack);
   return PDSUCCESS;
}


static inputDevice idNet = {
    .name = "ESP8266",
    .Init = NetInputInit,
    .next = NULL
};


void NetAdd(void)
{
    InDevListIns(&idNet);
}
